import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:icooker/model/meaildetail/CookStep.dart';
import 'package:icooker/model/meaildetail/MealDetailData.dart';
import 'package:icooker/providers/meal_details_provider.dart';
import 'package:kasax/kasax.dart';
import 'package:provider/provider.dart';

import 'bottom_menu.dart';

/// metail details
/// used static route forward
class MetailsDetailV1 extends StatefulWidget {
  const MetailsDetailV1({Key? key}) : super(key: key);

  @override
  _MetailsDetailV1State createState() => _MetailsDetailV1State();
}

class _MetailsDetailV1State extends State<MetailsDetailV1> {
  var provider = MealDetailsProvider();

  @override
  Widget build(BuildContext context) {
    var args = ModalRoute.of(context)!.settings.arguments;
    if (args == null) {
      return Container(
        child: buildLoadingWidget(),
      );
    }

    return ChangeNotifierProvider(
      create: (BuildContext context) {
        return provider;
      },
      child: FutureBuilder(
        future: provider.featchMealDetail(args: args),
        builder:
            (BuildContext context, AsyncSnapshot<MealDetailData?> snapshot) {
          if (snapshot != null &&
              snapshot.connectionState == ConnectionState.done &&
              snapshot.hasData &&
              snapshot.data != null) {
            var data = snapshot.data!;
            if (data != null) {
              return Scaffold(
                body: PageContainer(data!),
                bottomSheet: BottomMenu(data!)!,
              );
            }
          }
          return Scaffold(
            body: Container(
              child: buildLoadingWidget(),
            ),
          );
        },
      ),
    );
  }
}



class PageContainer extends StatelessWidget {
  MealDetailData data;

  PageContainer(this.data, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: [
        SliverPersistentHeader(
            pinned: true,
            floating: true,
            delegate: DetailAppbarDelegate(
                collaseHeight: 55,
                title: data.title!,
                expandedHeight: 320,
                authorImagUrl: data.author!.avatarUrl!,
                paddingTop: MediaQuery.of(context).padding.top,
                coverImgUrl: data.cover_img!.big!)),
        SliverToBoxAdapter(child: DescHeader(data)),
        CookStepList(data.cook_steps!)
      ],
    );
  }
}

class DescHeader extends StatelessWidget {
  MealDetailData data;

  DescHeader(this.data, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var secodaryIngredients = data.secondary_ingredient!
        .map((e) => "${e.title}: ${e.amount}")
        .toList();

    return Container(
      margin: EdgeInsets.only(top: 10, left: 16, right: 16, bottom: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "${data.title!} _ ${data.taste}",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(
            height: 10,
          ),
          Container(
            alignment: Alignment.bottomCenter,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Expanded(
                    child: Row(
                  children: [
                    CircleAvatar(
                      radius: 30,
                      backgroundImage: NetworkImage(data.author!.avatarUrl!),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(data.author!.nickname!),
                        Text("${data.comment_amount}篇作品"),
                      ],
                    )
                  ],
                )),
               // buildMenuContainer()
                ActionChip(label: Text("+ 关注"), onPressed: (){}),
              ],
            ),
          ),
          SizedBox(
            height: 5,
          ),
          RichText(
            text: TextSpan(
                text: "烹饪方式:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text: "${data.technology}",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
          RichText(
            text: TextSpan(
                text: "主料:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text:
                        "${data.main_ingredient![0].title} ${data.main_ingredient![0].amount}",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
          // Text("辅料: $secodaryIngredients"),
          RichText(
            text: TextSpan(
                text: "辅料:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text: "$secodaryIngredients",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
          RichText(
            text: TextSpan(
                text: "耗时:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text: "${data.cooking_time}",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
          RichText(
            text: TextSpan(
                text: "关于:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text: "${data.about_msj!.content!}",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
          SizedBox(
            height: 10,
          ),
        ],
      ),
    );
  }

  Container buildMenuContainer() {
    return Container(
                padding:
                    EdgeInsets.only(left: 16, right: 16, top: 5, bottom: 5),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(17),
                    color: Colors.red),
                child: RichText(
                  textAlign: TextAlign.center,
                  text: TextSpan(children: [
                    TextSpan(text: "+", children: [TextSpan(text: " 关注")])
                  ]),
                ),
              );
  }
}

class CookStepList extends StatelessWidget {
  List<CookStep> dataList;

  CookStepList(this.dataList, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
      var cookStep = dataList![index];
      return Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              AspectRatio(
                aspectRatio: 1 / 1,
                child: CachedNetworkImage(
                  fit: BoxFit.cover,
                  imageUrl: cookStep.pic_urls![0]!.big!,
                  placeholder: (
                    BuildContext context,
                    String url,
                  ) =>
                      Container(
                    color: Color(0xFFD6D6D6),
                    child: Center(
                      child: SizedBox(
                        width: 30,
                        height: 30,
                        child: CircularProgressIndicator(
                          color: Colors.blueGrey,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 5,
              ),
              Text(
                cookStep.content ?? "",
                style:
                    TextStyle(fontSize: 16, letterSpacing: 1, wordSpacing: 3),
              ),
              Divider()
            ],
          ),
          Positioned(
            child: Stack(
              children: [
                SizedBox(
                  width: 65,
                  height: 25,
                  child: Opacity(
                    opacity: 0.5,
                    child: Container(
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                            bottomRight: Radius.circular(16),
                            topRight: Radius.circular(16),
                          ),
                          color: Colors.white),
                    ),
                  ),
                ),
                Text(
                  cookStep.title ?? "",
                  style: TextStyle(
                      color: Colors.red,
                      fontWeight: FontWeight.bold,
                      fontSize: 16),
                )
              ],
            ),
            top: 10,
          ),
        ],
      );
    }, childCount: dataList.length));
  }
}

class DetailAppbarDelegate extends SliverPersistentHeaderDelegate {
  final double collaseHeight; // 收起高度
  final double expandedHeight; // 展开高度
  final double paddingTop; // 顶部边距
  final String coverImgUrl;
  final String authorImagUrl;
  final String title;
  String statusBarMode = 'dark';

  DetailAppbarDelegate(
      {this.collaseHeight = 80,
      this.expandedHeight = 120,
      this.paddingTop = 0,
      this.coverImgUrl = "",
      this.authorImagUrl = "",
      this.title = ""});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    this.updateStatusBarBrightness(shrinkOffset);
    return Container(
      height: this.maxExtent,
      width: MediaQuery.of(context).size.width,
      child: Stack(
        fit: StackFit.expand,
        children: [
          Container(
            // 背景图
            child: AspectRatio(
              aspectRatio: 1 / 1,
              child: CachedNetworkImage(
                fit: BoxFit.cover,
                imageUrl: coverImgUrl,
                placeholder: (
                  BuildContext context,
                  String url,
                ) =>
                    Container(
                  color: Color(0xFFD6D6D6),
                  child: Center(
                    child: SizedBox(
                      width: 30,
                      height: 30,
                      child: CircularProgressIndicator(
                        color: Colors.blueGrey,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
          // 收起头部
          Positioned(
              left: 0,
              top: 0,
              right: 0,
              child: Container(
                // 背景颜色
                color: this.makeStickyHeaderBgColor(shrinkOffset),
                child: SafeArea(
                  bottom: false,
                  // 收起的appbar
                  child: Container(
                    height: this.collaseHeight,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // 返回按钮
                        IconButton(
                          onPressed: () {},
                          icon: Icon(Icons.arrow_back_ios),
                          color: this
                              .makeStickyHeaderTextColor(shrinkOffset, true),
                        ),
                        Expanded(
                            child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Opacity(
                              opacity: shrinkOffset /
                                  (this.maxExtent - this.minExtent),
                              child: CircleAvatar(
                                backgroundImage: NetworkImage(authorImagUrl),
                              ),
                            ),
                            SizedBox(
                              width: 5,
                            ),
                            // 标题
                            Expanded(
                                child: Text(
                              this.title,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.w500,
                                  color: this.makeStickyHeaderTextColor(
                                      shrinkOffset, false)),
                            )),
                          ],
                        )),
                        // 分享
                        IconButton(
                          onPressed: () {},
                          icon: Icon(Icons.more),
                          color: this
                              .makeStickyHeaderTextColor(shrinkOffset, true),
                        )
                      ],
                    ),
                  ),
                ),
              ))
        ],
      ),
    );
  }

  @override
  double get maxExtent => this.expandedHeight;

  @override
  double get minExtent => this.collaseHeight + this.paddingTop;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }

  void updateStatusBarBrightness(double shrinkOffset) {
    if (shrinkOffset > 50 && this.statusBarMode == 'dart') {
      this.statusBarMode = 'light';
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
          statusBarBrightness: Brightness.light,
          statusBarIconBrightness: Brightness.light));
    } else if (shrinkOffset < 50 && this.statusBarMode == 'light') {
      this.statusBarMode = 'dark';
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
          statusBarBrightness: Brightness.dark,
          statusBarIconBrightness: Brightness.dark));
    }
  }

  makeStickyHeaderBgColor(double shrinkOffset) {
    final int alpha = (shrinkOffset / (this.maxExtent - this.minExtent) * 255)
        .clamp(0, 255)
        .toInt();
    return Color.fromARGB(alpha, 255, 255, 255);
  }

  makeStickyHeaderTextColor(double shrinkOffset, bool isIcon) {
    if (shrinkOffset <= 50) {
      return isIcon ? Colors.white : Colors.transparent;
    } else {
      final int alpha = (shrinkOffset / (this.maxExtent - this.minExtent) * 255)
          .clamp(0, 255)
          .toInt();
      return Color.fromARGB(alpha, 0, 0, 0);
    }
  }
}
